## -*- coding: utf-8 -*-
import sqlite3
from flask import Flask, request, jsonify
import requests, json
from flask_sqlalchemy import SQLAlchemy
from contextlib import closing
from flask import g
import time


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://nova_server:I0UGkUrUY6XoJMyQEwx9@172.16.82.209:3306/nova_cloud?charset=utf8'
db = SQLAlchemy(app)

DATABASE = 'api.db'

headers = {'Content-Type': 'application/json'}
api_gateway='https://cn-gateway.vnnox.com/oauth/clients'
api_gateway_refresh='https://cn-gateway.vnnox.com/actuator/refresh-clients'
password={'Authorization':'Basic YWRtaW46MTIzNDU2'}

def connect_db():
    return sqlite3.connect(DATABASE)

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('../db/init.sql') as f:
            db.cursor().executescript(f.read().decode('utf-8'))
        db.commit()
def query_db(query, args=(), one=False):
    cur = g.db.execute(query, args)
    rv = [dict((cur.description[idx][0], value)
               for idx, value in enumerate(row)) for row in cur.fetchall()]
    return (rv[0] if rv else None) if one else rv


@app.route('/')
def hello_world():
    return 'apigate边缘服务器'

@app.route('/test')
def Test():
    sql = 'insert into api_user(user,created) values(?,?) '
    cur = g.db.execute(sql,('lixl','2020-07-20'))
    g.db.commit()
    for user in query_db('select * from api_user'):
        print(user)


@app.route('/submit', methods=['POST'])
def Add_apigate():
    send = request.json
    user = request.json['user']
    zone =request.json['zone']
    print(user)
    q = "select uid from user where username = '%s' union select uid from user_conf where email = '%s'" %(user,user)
    uid = db.session.execute(q)
    print(q)
    result={'api': '0', 'spec': {'clientId': '', 'clientSecret': ''}, 'refresh': '', 'msg': ''}
    try:
        uid = list(uid)[0][0]
        print(uid)
        data={'userId':uid}
        print(data)
        if data:
            req = requests.post(api_gateway, data=data)
            if req.status_code == 200:
                sql = 'insert into api_user(user,zone,created,clientId,clientSecret) values(?,?,?,?,?) '
                print(req.json())
                clientId = req.json()['clientId']
                clientSecret = req.json()['clientSecret']
#                cur = g.db.execute(sql, (user, zone, time.strftime("%Y-%m-%d %H:%M", time.localtime()),clientId,clientSecret))
#                g.db.commit()
                result['api']=1
                result['spec']={'clientId':clientId,'clientSecret':clientSecret}
                refresh = requests.get(api_gateway_refresh, headers=password)
                if refresh.status_code==200:
                    result['refresh']=1
                    result['msg']='api开通成功'
                else:
                    result={'msg':'路由刷新失败'}
            else:
                result={'msg':'api开通失败'}
        else:
            result={'msg':'用户未找到'}
    except:
        result = {'msg': '用户未找到'}
    finally:
        print(result)
        return result
if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80,debug=True)